package com.kantboot.api.phone.service.impl;

import com.kantboot.api.phone.domain.dto.SmsSendDTO;
import com.kantboot.api.phone.domain.entity.ApiPhoneBelongTo;
import com.kantboot.api.phone.domain.entity.ApiPhoneSms;
import com.kantboot.api.phone.repository.ApiPhoneBelongToRepository;
import com.kantboot.api.phone.repository.ApiPhoneSmsRepository;
import com.kantboot.api.phone.service.IApiPhoneService;
import com.kantboot.api.qiucloud.serive.IApiQiniuSmsService;
import com.kantboot.util.common.exception.BaseException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class ApiPhoneServiceImpl implements IApiPhoneService {

    @Resource
    private ApiPhoneBelongToRepository repository;

    @Resource
    private ApiPhoneSmsRepository smsRepository;


    /**
     * 根据手机号获取归属地
     */
    @Override
    public ApiPhoneBelongTo getByPhoneBelongTo(String phone) {
        // 如果phone开头是"00"，则去掉"00"，改成"+"
        if (phone.startsWith("00")) {
            phone = "+" + phone.substring(2);
        }
        // 如果phone开头不是"+"，则加上"+86"
        if (!phone.startsWith("+")) {
            phone = "+86" + phone;
        }

        ApiPhoneBelongTo byPhone = repository.findByPhone(phone);
        if (byPhone == null) {
            throw BaseException.of("unknown", "未知归属地");
        }
        return byPhone;
    }

    @Resource
    private IApiQiniuSmsService apiQiniuSmsService;

    @Override
    public ApiPhoneSms send(SmsSendDTO dto) {
        // 默认`状态码`为“发送中”
        String statusCode = ApiPhoneSms.STATUS_CODE_SENDING;
        // 默认`失败原由`编码为空
        String failReasonCode = null;

        try{
            apiQiniuSmsService.sendFulltextMessageOne(dto.getTo(), dto.getContent());
            statusCode = ApiPhoneSms.STATUS_CODE_SUCCESS;
        }catch (BaseException e){
            // 如果发送失败，则状态码为“发送失败”
            statusCode = ApiPhoneSms.STATUS_CODE_FAIL;
            // 将`失败原由`编码设置为e.getStateCode()
            failReasonCode = e.getStateCode();
            ApiPhoneSms apiPhoneSms = new ApiPhoneSms()
                    .setTo(dto.getTo())
                    .setContent(dto.getContent())
                    .setTypeCode(dto.getTypeCode())
                    .setStatusCode(statusCode)
                    .setFailReasonCode(failReasonCode);
            smsRepository.save(apiPhoneSms);
            throw e;
        }

        ApiPhoneSms apiPhoneSms = new ApiPhoneSms()
                .setTo(dto.getTo())
                .setContent(dto.getContent())
                .setTypeCode(dto.getTypeCode())
                .setStatusCode(statusCode)
                .setFailReasonCode(failReasonCode);
        return smsRepository.save(apiPhoneSms);
    }
}
